'use strict';

var gulp        = require('gulp');                        //获取gulp
var browserSync = require('browser-sync').create();       //获取browsersync
var babel       = require("gulp-babel");
var reload      = browserSync.reload;
var proxy       = require('http-proxy-middleware'); // 要先安装 gulp-connect
var postcss = require('gulp-postcss');
var pxtoviewport = require('postcss-px-to-viewport');


// 设定项目名
let projectName = 'test';
let openVW = false;
let projectWidth = 750;

// es6 转码
var watcher = gulp.watch(`./projects/${projectName}/js/*.js`, ['babel']);
watcher.on('change', function(event) {
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
gulp.task("babel", function () {
  return gulp.src(`./projects/${projectName}/js/*.js`)
    .pipe(babel({
        presets: ['es2015']
    }))
    .pipe(gulp.dest(`./projects/${projectName}/dist/`));
});
// css转码
var watchercss = gulp.watch(`./projects/${projectName}/style/*.css`, ['css']);
watchercss.on('change', function(event) {
  console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
gulp.task('css', function () {
    if (openVW) {
        var processors = [
            pxtoviewport({
                viewportWidth: projectWidth,
                viewportUnit: 'vw'
            })
        ];
        return gulp.src([`./projects/${projectName}/style/*.css`])
        .pipe(postcss(processors))
        .pipe(postcss([require('postcss-write-svg')({})]))
        .pipe(gulp.dest(`./projects/${projectName}/dist/`));
    } else {
        return gulp.src([`./projects/${projectName}/style/*.css`])
        .pipe(gulp.dest(`./projects/${projectName}/dist/`));
    }
});
// 接口代理
var mockapiProxy = proxy('/api', {
    target: 'http://www.easy-mock.com/mock/59546b9b9adc231f356d1324/',
    changeOrigin: true,
    ws: true
});
var devapiProxy = proxy('/sales_api', {
    target: 'http://chjsuperchic.webapp.lmh5.com/mall/',
    changeOrigin: true,
    ws: true
});

// 静态服务器
gulp.task('browser-sync-default', function() {
    browserSync.init({
        server: {
            baseDir: "./projects/"
        }
    });
    gulp.watch(`projects/${projectName}/*.html`).on('change', reload);
    gulp.watch(`projects/${projectName}/dist/**`).on('change', reload);
});

// 代理
gulp.task('browser-sync-agency', function() {
    browserSync.init({
        port: 2017,
        server: {
            baseDir: ['./projects/']
        },
        middleware: [
            mockapiProxy,
            devapiProxy
        ]
    });
    gulp.watch(`projects/${projectName}/*.html`).on('change', reload);
    gulp.watch(`projects/${projectName}/dist/**`).on('change', reload);
});


gulp.task('default',['babel','css','browser-sync-default']);
gulp.task('agency',['babel','css','browser-sync-agency']);